package com.taikang.system.controller.admin;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.taikang.base.controller.BaseController;
import com.taikang.base.token.TokenValidate;
import com.taikang.base.util.NumberUtil;
import com.taikang.system.entity.SysRegion;
import com.taikang.system.form.SysRegionForm;
import com.taikang.system.service.ISysRegionService;

/**
 * 省市区的基础
 * @author taikang
 * @create-time 2015-10-8   下午12:19:23
 * @version 1.0
 */
@Controller("sysRegionController")
@Scope("prototype")
@RequestMapping(value = "/admin/system/region")
public class SysRegionController extends BaseController {

	@Resource(name = "sysRegionServiceImpl")
	private ISysRegionService sysRegionService;
	
	/**
	 * 首页
	 * @return 
	 */
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public String index(){
		return "/admin/system/sys_region_index";
	}
	/**
	 * 跳转到添加页面
	 * @return 
	 */
	@RequestMapping(value = "/add.htm", method = RequestMethod.GET)
	public ModelAndView add(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/system/sys_region_add");
		Map<String, Object> data = view.getModel();
		Long[] parentIds = NumberUtil.convertStringArrayToLongArray(model.getParentIds().split(","));
		SysRegion item = new SysRegion();
		item.setParentId(parentIds[parentIds.length - 1]);
		item.setLevel(model.getLevel());
		data.put("item", item);
		data.put("level",convertLevel(model.getLevel()));
		return view;
	}
	/**
	 * 返回对应的级别
	 * @param level
	 * @return
	 */
	private String convertLevel(Integer level) {
		String str = "";
		if (level == 1) {
			str = "省";
		}
		else if(level == 2)
		{
			str = "市";
		}else {
			str = "区";
		}
		return str;
	}
	
	/**
	 * 批量设置地区所属大区
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/batchFitArea.htm",method = RequestMethod.POST)
	public ModelAndView batchFitArea(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			sysRegionService.batchFitArea(NumberUtil.convertStringArrayToLongArray(model.getSelIds().split(",")), model.getCondition().getAreaId());
			return ajaxJSON(Status.success, "设置成功");
		} catch (Exception e) {
			String message = "批量设置地区发生异常:" + e.getMessage();
			logger.error(message, e);
			return ajaxJSON(Status.error, "设置失败");
		}
	}
	/**
	 * 设置区域所属大区
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/fitArea.htm",method = RequestMethod.POST)
	public ModelAndView fitArea(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			sysRegionService.fitArea(model.getCondition());
			return ajaxJSON(Status.success, "设置成功");
		} catch (Exception e) {
			String message = "设置区域所属大区发生异常: " +e.getMessage();
			logger.error(message, e);
			return ajaxJSON(Status.error,"设置失败");
		}
	}
	/**
	 * 移除已经设置的区域
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/removeArea.htm",method =RequestMethod.POST)
	public ModelAndView removeArea(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			sysRegionService.removeArea(model.getCondition());
			return ajaxJSON(Status.success, "移除成功");
		} catch (Exception e) {
			String msg = "移除已经设置的区域发生异常:" + e.getMessage();
			logger.error(msg, e);
			return ajaxJSON(Status.error, "移除失败");
		}
	}
	
	/**
	 * 批量移除已经设置的区域
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/batchRemoveArea.htm",method =RequestMethod.POST)
	public ModelAndView batchRemoveArea(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			sysRegionService.batchRemoveArea(NumberUtil.convertStringArrayToLongArray(model.getSelIds().split(",")));
			return ajaxJSON(Status.success, "移除成功");
		} catch (Exception e) {
			String msg = "移除已经设置的区域发生异常:" + e.getMessage();
			logger.error(msg, e);
			return ajaxJSON(Status.error, "移除失败");
		}
	}
	/**
	 * 分页查询
	 * @return 
	 */
	@RequestMapping(value = "/listSysRegionByPage.htm", method = RequestMethod.POST)
	public void listSysRegionByPage(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			sysRegionService.listSysRegionByPage(model.getPageResult(),model.getCondition());
			JSONObject root = toPageJson(model.getPageResult(), new String[]{"id","name","parentId","isHot","level","areaId","code","cityName","sort"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询省市区基础表时发生异常："+ex.getMessage();
			logger.error(msg,ex);
		}	
	}
	
	/**
	 * 选择下一级别省市区
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/selectNextLevel.htm",method = RequestMethod.POST)
	public void selectNextLevel(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			 List<SysRegion> regionList = sysRegionService.listSysregionByCondition(model.getCondition());
			 JSONObject root = new JSONObject();
			 root.put("regionList", regionList);
			 ajaxPageResult(root, response);
		} catch (Exception e) {
			String msg = "选择下一级别省市区发生异常:" + e.getMessage();
			logger.error(msg, e);
		}
	}
	/**
	 * 分页大区的详情查询
	 * @return 
	 */
	@RequestMapping(value = "/listSysRegionAreaDetailByPage.htm", method = RequestMethod.POST)
	public void listSysRegionAreaDetailByPage(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			sysRegionService.listSysRegionAreaDetailByPage(model.getPageResult(),model.getCondition());
			JSONObject root = toPageJson(model.getPageResult(), new String[]{"id","name","parentId","isHot","level","areaId","code","cityName"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询省市区基础表时发生异常："+ex.getMessage();
			logger.error(msg,ex);
		}	
	}
	/**
	 * 设置热门
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/setHot.htm",method = RequestMethod.POST)
	public ModelAndView setHot(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			sysRegionService.setHot(NumberUtil.convertStringArrayToLongArray(model.getSelIds().split(",")),model.getStatusHot());
			if (model.getStatusHot() == 0) {
				return ajaxJSON(Status.success,"取消热门成功");
			}else {
				return ajaxJSON(Status.success,"设置热门成功");
			}
			
		} catch (Exception e) {
			String msg = "设置热门时发生异常 : " +e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "设置热门失败");
		}
	}
	
	/**
	 * 保存省市区基础表
	 * @return 
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/system/sys_region_add");
		Map<String,Object> data = view.getModel();
		if(null != model.getItem().getId()){
			SysRegion item = sysRegionService.getSysRegionById(Long.valueOf(model.getItem().getId()));
			data.put("item", item);
			data.put("level",convertLevel(item.getLevel()));
		}
		return view;
	}
	
	/**
	 * 保存省市区基础表
	 * @return 
	 */
	@RequestMapping(value = "/saveSysRegion.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView saveSysRegion(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpSession session){
		try {
			if(null == model.getItem().getId()){
				sysRegionService.add(model.getItem());
			}else{
				sysRegionService.update(model.getItem());
			}
			return ajaxJSON(Status.success,"保存成功");
		} catch (Exception e) {
			String msg = "保存省市区基础表时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	
	/**
	 * 删除SysRegion
	 * @return 
	 */
	@RequestMapping(value = "/del.htm", method = RequestMethod.POST)
	public ModelAndView del(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			sysRegionService.delByIds(NumberUtil.convertStringArrayToLongArray(model.getSelIds().split(",")));
			return ajaxJSON(Status.success,"删除成功");
		} catch (Exception e) {
			String msg = "删除省市区基础表时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "删除失败，请稍后重试");
		}
	}
}

